import json

from flask import render_template, g, jsonify, request

from application.models import User
from application.modules.ranking import ranking_blue
from application.utils.common import user_login_data


@ranking_blue.route("/ranklist")
@user_login_data
def list():
    user = g.user
    if not user:
        return jsonify(errno=4011, errmsg="用户未登录")
    return render_template('ranking.html')

@ranking_blue.route('/ranking', methods=["POST", "GET"])
def ranking():
    users = User.query.order_by(User.sources.desc()).all()
    users_data = []
    for user in users:
        user_temp = {}
        user_temp['id'] = len(users_data) + 1
        user_temp['name'] = user.username
        user_temp['source'] = str(user.sources)
        user_temp['vip'] = "否"
        users_data.append(user_temp)
    return json.dumps(users_data)